
#include "SpeedMonitor.h"
#include "assert.h"

#include <stdio.h>


#define UPDATE_TIME 1000 //ms

SpeedMonitor::SpeedMonitor(Setting* setting) : m_setting(setting), m_counter(0), m_isFirst(true)
{
	m_timer = new QTimer(this);
	connect(m_timer, SIGNAL(timeout()), this, SLOT(caculateSpeed()));
	m_timer->start(UPDATE_TIME);
}
SpeedMonitor::~SpeedMonitor() 
{
	m_timer->stop();
	delete m_timer;
}


int SpeedMonitor::speed() const
{
	return m_speed;
}
void SpeedMonitor::caculateSpeed()
{
	static const float pi = 3.1415926;
	int preSpeed = m_speed;
	assert(m_setting);
	m_speed = (int)((2.0*pi*(float)m_setting->radius() * 10 * m_counter / 40) / (UPDATE_TIME / 1000));
	m_counter = 0;
	printf("m_speed = %d\n",	m_speed);
	if(m_speed == 0 && preSpeed != 0)
	{
		emit speedSignal(tr("Stop"));
	}
	if(m_speed != 0 && preSpeed == 0)
	{

		emit speedSignal(tr("Runing"));
	}
	if(m_isFirst)
	{
		m_isFirst = false;
		if(m_speed != 0)
		{
			emit speedSignal(tr("Runing"));
		}
		else
		{
			emit speedSignal(tr("Stop"));
		}
	}

}



void SpeedMonitor::update(const SensorState& state)
{

	if(state.state)
	{
		m_counter++;
	}
}
